<template>
  <q-page>
    <div class="container" v-if="!loading">
      <q-tabs v-model="action">
        <q-tab name="team" label="可用阵容"/>
        <q-tab name="box" label="box配置"/>
        <q-tab name="calc" label="分刀计算"/>
      </q-tabs>
      <q-tab-panels v-model="action">
        <q-tab-panel name="team">
          <div class="row q-col-gutter-md">
            <div class="col-12">
              <div class="row q-col-gutter-md">
                <div class="col-xs-12 col-sm-4">
                  <q-btn class="full-width" label="新增阵容" color="primary" @click="onAddTeamEvent"/>
                </div>
                <div class="col-xs-6 col-sm-4">
                  <q-btn class="full-width" label="导出阵容" color="orange" @click="exportLocalTeams"/>
                </div>
                <div class="col-xs-6 col-sm-4">
                  <q-btn class="full-width" label="导入阵容" color="purple" @click="importLocalTeams"/>
                </div>
              </div>
            </div>
            <div class="col-12 text-h6">
              本地阵容
            </div>
            <div class="col-12" v-if="localTeams && localTeams.length > 0 && fullList">
              <div class="row q-col-gutter-sm">
                <div v-for="(item, key) in localTeams"
                     :key="key"
                     class="col-xs-12 col-sm-6">
                  <transition appear
                              appear-active-class="animated fadeInLeft"
                              leave-active-class="animated fadeOutLeft">
                    <q-card>
                      <team :team="item" :full-character-list="fullList">
                        <template v-slot:top-right>
                          <div class="q-pa-sm">
                            <div class="row q-gutter-sm items-center">
                              <q-btn flat round size="sm" icon="backup" @click="doUploadTeam(item)"/>
                              <q-btn flat round size="sm" icon="share" @click="doExportTeam(item)"/>
                              <q-btn flat round size="sm" icon="edit" @click="onEditTeamEvent(key)"/>
                              <q-btn flat round size="sm" icon="delete" @click="onRemoveLocalTeamEvent(key)"/>
                              <q-btn flat round size="sm"
                                     :text-color="item.disable ? 'red' : 'green'"
                                     :icon="item.disable ? 'clear' : 'check'"
                                     @click="$store.commit('teams/update',
                                     {
                                       index: key,
                                       team: {
                                         ...item,
                                         disable: item.disable ? false : true
                                       }
                                     });" />
                            </div>
                          </div>
                        </template>
                      </team>
                    </q-card>
                  </transition>
                </div>
              </div>
            </div>
            <div class="col-12 text-caption text-grey" v-else>
              当前没有可用的本地阵容
            </div>
            <div class="col-12 text-h6">
              参考阵容
            </div>
            <div class="col-12 text-caption text-grey">
              <div class="row" v-if="battleName">
                当前使用的档案是
                <div class="text-bold text-red">{{ battleName }}</div>
                的队伍档案，你可以点击某一个队伍右上角的开关来禁止/允许一个阵容加入计算。
              </div>
            </div>
            <div class="col-12" v-if="onlineTeams && onlineTeams.length > 0">
              <div class="row q-col-gutter-sm">
                <div v-for="(item, key) in onlineTeams"
                     :key="key"
                     class="col-xs-12 col-sm-6">
                  <transition appear
                              appear-active-class="animated fadeInLeft"
                              leave-active-class="animated fadeOutLeft">
                    <q-card>
                      <team :team="item" :full-character-list="fullList">
                        <template v-slot:top-right>
                          <div class="q-pa-sm">
                            <div class="row q-gutter-sm items-center">
                              <q-btn flat round size="sm" icon="mdi-download" @click="saveTeamToLocal(item)"/>
                              <q-btn flat round size="sm" icon="delete" @click="doDeleteTeam(item.id)"/>
                              <q-toggle label="禁用" color="red" v-model="item.disable" />
                            </div>
                          </div>
                        </template>
                      </team>
                    </q-card>
                  </transition>
                </div>
              </div>
            </div>
            <div class="col-12 text-caption text-grey" v-else>
              当前没有可用的参考阵容
            </div>
          </div>
        </q-tab-panel>
        <q-tab-panel name="box">
          <div class="row q-col-gutter-md">
            <div class="col-12">
              点击角色头像以排除/启用某一名角色。<br/>
              在本页面排除/启用角色都是临时的，离开页面后配置将会丢失。
            </div>
            <div class="col-12">
              <character-list v-model="calcBox" @click="onBoxItemClickEvent"/>
            </div>
          </div>
        </q-tab-panel>
        <q-tab-panel name="calc">
          <div class="row q-col-gutter-md">
            <div class="col-12">
              <div class="row q-gutter-md items-center">
                <div>排序方式</div>
                <div>
                  <q-btn-toggle v-model="sortMode"
                                :options="[
                                { label: '按伤害量', value: 'damage' },
                                { label: '按得分', value: 'score' }]"/>
                </div>
              </div>
            </div>
            <div class="col-12">
              <div class="row q-gutter-md items-center">
                <div>轮次筛选</div>
                <div>
                  <div class="row q-gutter-md items-center">
                    <q-checkbox v-model="calcRound" :val="1" label="A"/>
                    <q-checkbox v-model="calcRound" :val="2" label="B"/>
                    <q-checkbox v-model="calcRound" :val="3" label="C"/>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-12">
              <div class="row q-gutter-md items-center">
                <div>BOSS筛选</div>
                <div>
                  <div class="row q-gutter-md items-center">
                    <q-checkbox v-model="calcBoss" :val="1" label="1"/>
                    <q-checkbox v-model="calcBoss" :val="2" label="2"/>
                    <q-checkbox v-model="calcBoss" :val="3" label="3"/>
                    <q-checkbox v-model="calcBoss" :val="4" label="4"/>
                    <q-checkbox v-model="calcBoss" :val="5" label="5"/>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-12">
              <div class="row q-gutter-md items-center">
                <div>结果数量上限</div>
                <q-btn-toggle v-model="displayTeamsCount"
                              :options="[
                                { label: '10', value: 10 },
                                { label: '20', value: 20 },
                                { label: '50', value: 50 },
                                { label: '100', value: 100 },
                                { label: '全部', value: -1 }]"/>
              </div>
            </div>
            <div class="col-12">
              <div class="row q-gutter-md">
                <q-btn color="primary" label="计算可用三刀阵容" @click="doCalculateTeams(3)"/>
                <q-btn color="secondary" label="计算可用两刀阵容" @click="doCalculateTeams(2)"/>
              </div>
            </div>
            <div class="col-12">
              <div v-if="calculating">
                <q-spinner/>
                计算中，请稍候……
              </div>
              <div v-else-if="!calculatedTeams">
                请点击上方的按钮进行计算。
              </div>
              <div class="" v-else-if="calculatedTeams && calculatedTeams.length === 0">
                没有计算出可用的分刀方案……
              </div>
              <div class="" v-else-if="calculatedTeams">
                成功计算出了{{ calculatedTeams.length }}个分刀方案：
              </div>
            </div>
            <div class="col-12" v-if="!calculating && calculatedTeams && calculatedTeams.length > 0">
              <div class="row q-col-gutter-sm">
                <div v-for="(teamGroup, teamGroupkey) in calculatedTeams"
                     :key="teamGroupkey"
                     class="col-xs-12 col-sm-6">
                  <transition appear
                              appear-active-class="animated fadeInLeft"
                              leave-active-class="animated fadeOutLeft">
                    <team-group :team-group="teamGroup" :full-character-list="fullList"/>
                  </transition>
                </div>
              </div>
            </div>
          </div>
        </q-tab-panel>
      </q-tab-panels>
    </div>
    <div class="container" v-else-if="loading">
      <div class="text-center">
        <q-spinner/>
        {{ loading }}
      </div>
    </div>
    <q-dialog v-model="addTeamDialogDisplay">
      <q-card style="width: 75%; min-width: 300px">
        <q-card-section>
          <div class="row q-gutter-md items-center">
            <div class="text-h6">{{ (addTeam.editType === 'add') ? '新增队伍档案' : '编辑队伍档案' }}</div>
            <q-space/>
            <q-btn flat round icon="clear" v-close-popup/>
          </div>
        </q-card-section>
        <q-card-section>
          <div class="row q-col-gutter-md" v-if="addTeam.team">
            <div class="col-12">
              <div class="row q-col-gutter-md items-center">
                <div class="col-12">
                  <div class="text-caption text-grey">
                    设定完毕后，请务必点击最下方的按钮保存更改。
                  </div>
                </div>
                <div class="col-12">
                  <q-input label="队伍名称" v-model="addTeam.team.name"/>
                </div>
                <div class="col-auto">
                  <q-btn-toggle toggle-color="primary"
                                v-model="addTeam.team.round"
                                spread
                                :options="[
                                  {label: 'A', value: 1},
                                  {label: 'B', value: 2},
                                  {label: 'C', value: 3}
                                  ]"/>
                </div>
                <div class="col">
                  <q-select emit-value
                            v-model="addTeam.team.boss"
                            map-options
                            :options="[
                              { label: 'Boss1', value: 1 },
                              { label: 'Boss2', value: 2 },
                              { label: 'Boss3', value: 3 },
                              { label: 'Boss4', value: 4 },
                              { label: 'Boss5', value: 5 }
                            ]"/>
                </div>
                <div class="col-12">
                  <div class="row q-col-gutter-md">
                    <div class="col-6">
                      <q-input label="最低标伤（万）"
                               type="number"
                               v-model.number="addTeam.team.damage[0]"
                               @blur="addTeam.team.damage =
                                [
                                  addTeam.team.damage[0],
                                  (addTeam.team.damage[0] > addTeam.team.damage[1]) ?
                                    addTeam.team.damage[0] :
                                    addTeam.team.damage[1]
                                ]"/>
                    </div>
                    <div class="col-6">
                      <q-input label="最高标伤（万）"
                               type="number"
                               v-model.number="addTeam.team.damage[1]"
                               @blur="addTeam.team.damage = [
                                 (addTeam.team.damage[0] > addTeam.team.damage[1]) ?
                                   addTeam.team.damage[1] :
                                   addTeam.team.damage[0],
                                 addTeam.team.damage[1]]"/>
                    </div>
                  </div>
                </div>
                <div class="col-12">
                  <div class="row q-col-gutter-sm">
                    <div class="gt-xs col-1"/>
                    <div v-for="(character, cKey) in addTeam.team.characters"
                         :key="cKey"
                         class="col-xs col-sm-2">
                      <div class="relative-position"
                           @click="onAddTeamCharacterClick(cKey)"
                           v-if="typeof character === 'number' && character <= 0">
                        <character avatar="img/character/yuki.jpg"
                                   :display-name="false"
                                   style="width: 100%"/>
                        <q-img class="absolute-top"
                               style="border-radius: 6px"
                               src="img/character/add.png"
                               width="100%"/>
                      </div>
                      <div @click="onEditTeamCharacterClick(cKey)" v-else>
                        <character :avatar="getCharacterById(character).avatar"
                                   :display-name="false"/>
                      </div>
                    </div>
                    <div class="gt-xs col-1"/>
                  </div>
                </div>
                <div class="col-12">
                  时间轴
                </div>
                <div class="col-12">
                  <q-list dense>
                    <q-item v-for="(action, aKey) in addTeam.team.actions"
                            :key="aKey" dense>
                      <q-item-section side>
                        <q-item-label>{{ toActionTime(action.time) }}</q-item-label>
                        <q-popup-edit v-model.number="addTeam.team.actions[aKey].time"
                                      :validate="v => v > 0 && v < 90"
                                      @hide="v => v > 0 && v < 90"
                                      buttons
                                      @save="addTeam.team.actions.sort((a, b) => b.time - a.time)">
                          <q-input type="number"
                                   v-model.number="action.time"
                                   hint="输入一个0-90之间的整数"/>
                        </q-popup-edit>
                      </q-item-section>
                      <q-item-section side>
                        <q-item-label>{{ getCharacterById(action.character).name || '？？？' }}</q-item-label>
                        <q-popup-edit v-model="addTeam.team.actions[aKey].character"
                                      :validate="v => addTeam.team.characters.indexOf(v) >= 0"
                                      @hide="v => addTeam.team.characters.indexOf(v) >= 0"
                                      buttons v-if="actionCharacterOptions.length > 0">
                          <q-select v-model="addTeam.team.actions[aKey].character"
                                    :options="actionCharacterOptions"
                                    emit-value
                                    map-options/>
                        </q-popup-edit>
                      </q-item-section>
                      <q-item-section>
                        <q-item-label>{{ action.detail }}</q-item-label>
                        <q-popup-edit v-model.number="addTeam.team.actions[aKey].detail"
                                      :validate="v => v.length > 0"
                                      @hide="v => v.length > 0"
                                      buttons>
                          <q-input v-model="addTeam.team.actions[aKey].detail"
                                   hint="对于本次行动的描述"/>
                        </q-popup-edit>
                      </q-item-section>
                      <q-item-section side>
                        <q-btn round flat size="sm" icon="delete" @click="onDeleteActionEvent(aKey)"/>
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-btn class="full-width"
                             dense
                             flat
                             label="新增一行"
                             @click="onActionsAddNewAction(addTeam.team.actions.length)"/>
                    </q-item>
                  </q-list>
                </div>
                <div class="col-12">
                  说明
                </div>
                <div class="col-12">
                  <q-input type="textarea" rows="5" v-model="addTeam.team.description"/>
                </div>
                <div class="col-12" v-if="addTeam.editType === 'add'">
                  <q-btn class="full-width"
                         color="primary"
                         :disable="(addTeam.team.characters.indexOf(0) >= 0)"
                         label="新增队伍"
                         v-if="addTeam.team && addTeam.team.characters"
                         @click="doAddTeam"/>
                </div>
                <div class="col-12" v-if="addTeam.editType === 'edit'">
                  <q-btn class="full-width"
                         color="primary"
                         :disable="(addTeam.team.characters.indexOf(0) >= 0)"
                         label="保存队伍"
                         v-if="addTeam.team && addTeam.team.characters"
                         @click="doEditTeam"/>
                </div>
              </div>
            </div>
          </div>
          <div v-else>
            喵喵喵？好像出现了一些问题呢
          </div>
        </q-card-section>
      </q-card>
      <!--添加角色对话框-->
      <add-character v-model="addTeam.addCharacterDialogDisplay"
                     :list="getRestList()"
                     @click="onAddTeamCharacterEvent"/>
      <!--编辑角色对话框-->
      <edit-character v-model="addTeam.editCharacterDialogDisplay"
                      :team-mode="true"
                      :data="addTeam.characterData"
                      :info="addTeam.characterInfo"
                      @update="onEditTeamCharacterUpdate"
                      @remove="onRemoveTeamCharacterEvent"/>
    </q-dialog>
  </q-page>
</template>

<script>
import Teams from 'src/lib/api/team.js'
import CharacterApi from "src/lib/api/characterInfo";
import {defaultValue, calcTeam} from 'src/lib/util/team.js';
import Team from "components/Team";
import TeamGroup from "components/TeamGroup";
import CharacterList from "components/CharacterList";
import AddCharacter from "components/AddCharacter";
import Character from "components/Character";
import {copyToClipboard, extend, format} from 'quasar';
import BigFun from "src/lib/api/bigfun";
import EditCharacter from "components/EditCharacter";
import Guild from "src/lib/api/guild";

const {pad} = format;

export default {
  name: "TeamCalculate",
  components: {EditCharacter, Character, AddCharacter, CharacterList, TeamGroup, Team},
  data: () => {
    return {
      loading: null,
      action: 'team',

      calcBox: null,

      fullList: null,
      battleName: null,
      fullTeamData: null,
      onlineTeams: null,
      disabledOnlineTeams: null,
      disabledLocalTeams: null,

      addTeamDialogDisplay: false,

      calculatedTeams: null,
      calculating: false,
      displayTeamsCount: 10,
      calcRound: [3],
      calcBoss: [1, 2, 3, 4, 5],
      scoreBase: [
        [1.2, 1.2, 1.3, 1.4, 1.5],
        [1.6, 1.6, 1.8, 1.9, 2],
        [2, 2, 2.5, 2.5, 3]
      ],
      sortMode: 'score',

      addTeam: {
        editType: 'add',
        editTeam: null,

        actionIndex: null,

        team: null,
        characterData: null,
        characterInfo: null,
        addCharacterDialogDisplay: false,
        editCharacterDialogDisplay: false
      }
    };
  },
  watch: {
    /*
    'addTeam.team': {
      handler: function (v, o) {
        if (!v) return;
        if (!v.damage[0] || v.damage[0] < 0) this.addTeam.team.damage[0] = 0;
        if (!v.damage[1] || v.damage[1] < 0) this.addTeam.team.damage[1] = 0;
        if (v.damage[0] > v.damage[1]) {
          // 把大的变小，就让小的一起变小
          if (v.damage[1] !== o.damage[1]) this.addTeam.team.damage[0] = v.damage[1];
          // 把小的变大，就让大的一起变大
          else if (v.damage[0] !== o.damage[0]) this.addTeam.team.damage[1] = v.damage[0];
          else {
            const t = v.damage[0];
            this.addTeam.team.damage[0] = v.damage[1];
            this.addTeam.team.damage[1] = t;
          }
        }
      },
      deep: true
    }
     */
  },
  computed: {
    box: {
      get() {
        return this.$store.getters['box/box'];
      }
    },
    teams: {
      get() {
        let teams = (this.onlineTeams || []).concat(this.localTeams || []);
        return teams;
      }
    },
    localTeams: {
      get() {
        let localTeams = this.$store.getters['teams/teams'];
        return localTeams;
      }
    },
    actionCharacterOptions: {
      get() {
        if (!this.addTeam.team || !this.addTeam.team.characters) return [];
        let list = [{
          label: '不指定',
          value: 0
        }];
        this.addTeam.team.characters.forEach(c => {
          if (c) list.push({
            label: this.getCharacterById(c).name || '？？？',
            value: c
          })
        });
        return list;
      }
    }
  },
  methods: {
    onAddTeamEvent() {
      this.addTeam.editType = 'add';
      this.addTeam.team = defaultValue();
      this.addTeamDialogDisplay = true;
    },
    onEditTeamEvent(localTeam) {
      this.addTeam.editType = 'edit';
      this.editTeam = localTeam;
      this.addTeam.team = JSON.parse(JSON.stringify(this.localTeams[localTeam]));
      // console.log(this.addTeam.team);
      this.addTeamDialogDisplay = true;
    },
    doAddTeam() {
      this.$store.commit('teams/add', this.addTeam.team);
      this.addTeamDialogDisplay = false;
    },
    doEditTeam() {
      this.$store.commit('teams/update', {index: this.editTeam, team: this.addTeam.team});
      this.addTeamDialogDisplay = false;
    },
    onRemoveLocalTeamEvent(index) {
      let that = this;
      this.$q.dialog({
        title: '确认删除',
        message: `确认要删除<strong>${this.localTeams[index].name}</strong>的队伍数据吗？你保存的信息都将丢失！`,
        html: true,
        cancel: true,
        persistent: true
      }).onOk(function () {
        that.$store.commit('teams/remove', index);
      })
    },
    onUploadTeamEvent() {

    },
    onAddTeamCharacterClick(index) {
      this.actionIndex = index;
      this.addTeam.addCharacterDialogDisplay = true;
    },
    onAddTeamCharacterEvent(id) {
      this.$set(this.addTeam.team.characters, this.actionIndex, id);
      this.$set(this.addTeam.team.filter, id, {});
      this.addTeam.addCharacterDialogDisplay = false;
    },
    async onEditTeamCharacterClick(index) {
      this.$q.loading.show();
      this.addTeam.actionIndex = index;
      this.addTeam.characterInfo = await this.onLoadCharacterInfo(this.addTeam.team.characters[index]);
      const cFilter = extend(true, this.addTeam.team.filter[this.addTeam.team.characters[index]], {});
      this.addTeam.characterData = cFilter;
      this.addTeam.editCharacterDialogDisplay = true;
      this.$q.loading.hide();
    },
    onEditTeamCharacterUpdate(data) {
      const id = data.id;
      const filter = data.filter;
      this.$set(this.addTeam.team.filter, id, filter);
    },
    onRemoveTeamCharacterEvent(id) {
      for (const i in this.addTeam.team.characters) {
        if (this.addTeam.team.characters[i] === id) {
          this.$set(this.addTeam.team.characters, i, 0);
          for (let i in this.addTeam.team.actions) {
            if (this.addTeam.team.actions[i].character === id)
              this.$set(this.addTeam.team.actions[i], 'character', 0);
          }
          break;
        }
      }
      ;
      this.addTeam.characterData = null;
      this.addTeam.characterInfo = null;
      this.addTeam.editCharacterDialogDisplay = false;
    },
    onActionsAddNewAction(location) {
      const lastTime = (this.addTeam.team.actions && this.addTeam.team.actions[this.addTeam.team.actions.length - 1]) ?
        this.addTeam.team.actions[this.addTeam.team.actions.length - 1].time : 80;
      this.addTeam.team.actions.splice(location, 0, {
        time: lastTime,
        character: 0,
        detail: '平A后UB'
      })
    },
    onDeleteActionEvent(index) {
      if (this.addTeam.team.actions && this.addTeam.team.actions[index]) this.addTeam.team.actions.splice(index, 1);
    },
    async onLoadCharacterInfo(id) {
      try {
        const i = await BigFun.getCharacterInfo(id);
        let characterInfo;
        if (i.length > 0) characterInfo = i[0];
        characterInfo.name = this.getCharacterById(id).name;
        return characterInfo;
      } catch {
        return {
          name: this.getCharacterById(id).name
        }
      }
    },
    getRestList() {
      if (!this.fullList) return [];
      let box = this.addTeam.team.characters || [];
      let list = [];
      for (const i of this.fullList) {
        let has = false;
        for (const j of box) {
          if (i.id === j) {
            has = true;
            break;
          }
        }
        if (!has) list.push(i);
      }
      return list;
    },
    getCharacterById(id) {
      for (const i of this.fullList) {
        if (id === i.id) return i;
      }
      return {};
    },
    async doCalculateTeams(count) {
      this.calculating = true;
      let that = this;
      const calcFunc = () => {
        return new Promise((resolve, reject) => {
          // setTimeout(() => {}, 200);
          const cTeams = calcTeam(
            that.teams.filter(t => {
              if (t.disable) return false;
              return (that.calcRound.indexOf(t.round) > -1) && (that.calcBoss.indexOf(t.boss) > -1);
            }),
            that.calcBox.filter(i => {
              return !i.disable;
            }),
            count);
          const getDamageInstance = (array, base) => {
            let low = 0;
            let high = 0;
            array.forEach(i => {
              const data = Object.values(i.damage);
              data.sort((a, b) => Number.parseInt(a) < Number.parseInt(b));
              const keys = Object.keys(data);
              low += data[keys[0]] * (base ? base[i.round - 1][i.boss - 1] : 1);
              high += data[keys[keys.length - 1]] * (base ? base[i.round - 1][i.boss - 1] : 1);
            });
            return [low, high];
          }
          if (this.sortMode === 'damage') {
            cTeams.sort((a, b) => {
              let aDamage = [0, 0];
              let bDamage = [0, 0];
              aDamage = getDamageInstance(a);
              bDamage = getDamageInstance(b);
              console.log(aDamage, bDamage);
              return (bDamage[0] + bDamage[1]) / 2 - (aDamage[0] + aDamage[1]) / 2;
            })
          } else {
            cTeams.sort((a, b) => {
              let aDamage = [0, 0];
              let bDamage = [0, 0];
              aDamage = getDamageInstance(a, this.scoreBase);
              bDamage = getDamageInstance(b, this.scoreBase);
              console.log(aDamage, bDamage);
              return (bDamage[0] + bDamage[1]) / 2 - (aDamage[0] + aDamage[1]) / 2;
            })
          }
          const result = [];
          for (let t of cTeams) {
            if (this.displayTeamsCount === -1 || result.length < this.displayTeamsCount) result.push({
              damage: getDamageInstance(t),
              teams: t
            })
          }
          ;
          setTimeout(() => {
            resolve(result);
          }, 0);
        })
      };
      // console.log('开始计算');
      this.calculatedTeams = await calcFunc();
      // console.log('计算完毕');
      this.calculating = false;
      // console.log('关闭等待');
    },
    onBoxItemClickEvent(id) {
      for (const i in this.calcBox) {
        if (this.calcBox[i].id === id) {
          this.$set(this.calcBox[i], 'disable', this.calcBox[i].disable ? false : true);
          break;
        }
      }
    },
    toActionTime(time) {
      return `${Math.floor(time / 60)}:${pad(`${time % 60}`, 2)}`;
    },
    importLocalTeams() {
      this.$q.dialog({
        title: '导入队伍数据',
        message: '请将使用本工具导出的文本复制到下方的文本框内：',
        prompt: {
          model: '',
          type: 'text' // optional
        },
        cancel: true,
        persistent: true
      }).onOk(data => {
        this.$q.dialog({
          title: '确认导入',
          message: '确认要导入队伍信息吗？',
          cancel: true,
          persistent: true
        }).onOk(() => {
          try {
            const teams = JSON.parse(decodeURI(atob(data)));
            this.$store.commit('teams/importTeams', teams.teams);
            this.$q.notify({
              message: '成功',
              caption: '已成功导入队伍信息。',
              icon: 'check'
            });
          } catch (e) {
            this.$q.notify({
              message: '失败',
              caption: '导入队伍信息失败。',
              icon: 'clear'
            });
          }
        })
      })
    },
    exportLocalTeams() {
      try {
        const base64 = btoa(encodeURI(JSON.stringify(this.$store.getters['teams/teams'])));
        copyToClipboard(base64).then(() => {
            this.$q.notify({
              message: '成功',
              caption: '已成功将本地队伍复制到剪切板。',
              icon: 'check'
            });
          }
        ).catch(() => {
          this.$q.notify({
            message: '失败',
            caption: '复制本地队伍到剪切板失败。',
            icon: 'clear'
          });
          this.$q.dialog({
            title: '手动复制',
            message: '请手动复制下方框内的文本：',
            prompt: {
              model: base64,
              type: 'text'
            }
          });
        })
      } catch (e) {
        this.$q.notify({
          message: '失败',
          caption: '生成本地队伍编码失败。',
          icon: 'clear'
        });
      }
    },
    doExportTeam(team) {
      try {
        const text = JSON.stringify(team)
        copyToClipboard(text).then(() => {
          this.$q.notify({
            message: '成功',
            caption: '已成功将队伍复制到剪切板。',
            icon: 'check'
          });
        }).catch(() => {
          this.$q.notify({
            message: '失败',
            caption: '复制队伍到剪切板失败。',
            icon: 'clear'
          });
          this.$q.dialog({
            title: '手动复制',
            message: '请手动复制下方框内的文本：',
            prompt: {
              model: team,
              type: 'text'
            }
          });
        })
      } catch (e) {
        this.$q.notify({
          message: '失败',
          caption: '生成队伍数据失败。',
          icon: 'clear'
        });
      }
    },
    async doUploadTeam(team) {
      this.$q.dialog({
        title: '确认上传',
        message: '确认要上传队伍信息到服务器吗？',
        cancel: true,
        persistent: true
      }).onOk(async () => {
        this.$q.loading.show();
        try {
          if (await Guild.uploadTeam(team)) {
            this.$q.notify({
              message: '成功',
              caption: '已成功上传队伍信息到服务器。',
              icon: 'check'
            });
            await this.getTeamData();
          }
        } catch (e) {
          this.$q.notify({
            message: '失败',
            caption: '上传队伍信息到服务器失败。',
            icon: 'clear'
          });
        }
        this.$q.loading.hide();
      })
    },
    async doDeleteTeam (id) {
      this.$q.dialog({
        title: '确认删除',
        message: '确认要在服务器上删除这个队伍吗？',
        cancel: true,
        persistent: true
      }).onOk(async () => {
        this.$q.loading.show();
        try {
          if (await Guild.deleteTeam(id)) {
            this.$q.notify({
              message: '成功',
              caption: '已成功在服务器删除这个队伍。',
              icon: 'check'
            });
            await this.getTeamData();
          }
        } catch (e) {
          this.$q.notify({
            message: '失败',
            caption: '在服务器删除这个队伍失败。',
            icon: 'clear'
          });
        }
        this.$q.loading.hide();
      })
    },
    saveTeamToLocal (team) {
      this.$store.commit('teams/add', team);
      this.$q.notify({
        message: '完成',
        caption: '已将该队伍保存到本地。',
        icon: 'info'
      });
    },
    async getTeamData () {
      this.loading = '正在加载参考阵容档案……';
      try {
        this.fullTeamData = null;
        this.fullTeamData = await Guild.teamList();
        const keys = Object.keys(this.fullTeamData);
        this.battleName = this.fullTeamData[keys[keys.length - 1]].name;
        this.onlineTeams = this.fullTeamData[keys[keys.length - 1]].teams;
        console.log(this.fullTeamData);
        this.onlineTeams.sort((a, b) => {
          if (a.round < b.round) return -1;
          return a.boss - b.boss;
        })
        for (const i in this.onlineTeams) {
          this.$set(this.onlineTeams[i], 'disable', false);
          try {
            // 不要影响页面正常工作（
            this.onlineTeams[i].actions.sort((a, b) => {
              return b.time - a.time;
            });
          } catch {
          }
        }
      } catch {}
      this.loading = null;
    }
  },
  async mounted() {
    this.addTeam.team = defaultValue();
    this.loading = '正在加载角色列表……';
    this.fullList = await CharacterApi.getCharacterList();
    // 生成计算box档案
    const box = this.box;
    let list = [];
    for (const i of box) {
      const c = this.getCharacterById(i.id);
      if (this.fullList && c) list.push({
        star: i.star,
        rank: i.rank,
        equipment: extend(true, i.equipment, []),
        weapon: i.weapon,
        disable: false,
        ...c
      });
    }
    this.calcBox = list;

    await this.getTeamData();
  }
}
</script>

<style scoped>

</style>
